<template>
	<view class="add-account">
		<!-- 类型切换 -->
		<view class="type-tabs">
			<view 
				class="type-tab" 
				:class="{ active: form.type === '支出' }"
				@tap="changeType('支出')"
			>
				<text class="type-text">支出</text>
			</view>
			<view 
				class="type-tab" 
				:class="{ active: form.type === '收入' }"
				@tap="changeType('收入')"
			>
				<text class="type-text">收入</text>
			</view>
		</view>

		<!-- 金额输入 -->
		<view class="amount-section">
			<text class="currency">¥</text>
			<input 
				class="amount-input" 
				type="digit" 
				v-model="form.amount"
				placeholder="0.00"
				placeholder-class="amount-placeholder"
				@focus="onAmountFocus"
				@blur="onAmountBlur"
			/>
		</view>

		<!-- 分类选择 -->
		<view class="category-section">
			<view class="section-title">选择分类</view>
			<scroll-view class="category-list" scroll-x>
				<view 
					v-for="item in categories" 
					:key="item._id"
					class="category-item"
					:class="{ active: form.category_id === item._id }"
					@tap="selectCategory(item)"
				>
					<view class="category-icon">
						<text class="iconfont" :class="item.icon || 'icon-qita'"></text>
					</view>
					<text class="category-name">{{ item.name }}</text>
				</view>
				<!-- 添加自定义分类 -->
				<view class="category-item add-category" @tap="goToAddCategory">
					<view class="category-icon">
						<text class="iconfont icon-add">+</text>
					</view>
					<text class="category-name">添加</text>
				</view>
			</scroll-view>
		</view>

		<!-- 其他信息 -->
		<view class="form-section">
			<!-- 日期 -->
			<view class="form-item">
				<text class="form-label">日期</text>
				<picker mode="date" :value="form.date" @change="onDateChange">
					<view class="form-value">
						<text>{{ form.date }}</text>
						<text class="iconfont icon-arrow">›</text>
					</view>
				</picker>
			</view>

			<!-- 备注 -->
			<view class="form-item">
				<text class="form-label">备注</text>
				<input 
					class="form-input" 
					v-model="form.note" 
					placeholder="添加备注（可选）"
					maxlength="50"
				/>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="footer">
			<button class="submit-btn" @tap="submitForm" :disabled="!canSubmit">
				{{ isEdit ? '保存修改' : '完成记账' }}
			</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			form: {
				type: '支出',
				amount: '',
				category_id: '',
				note: '',
				date: ''
			},
			categories: [],
			isEdit: false,
			recordId: ''
		}
	},
	computed: {
		canSubmit() {
			return this.form.amount && parseFloat(this.form.amount) > 0 && this.form.category_id
		}
	},
	onLoad(options) {
		// 初始化日期为今天
		this.form.date = this.getToday()
		
		// 加载分类
		this.loadCategories()
		
		// 如果是编辑模式
		if (options.id) {
			this.isEdit = true
			this.recordId = options.id
			this.loadRecord()
		}
	},
	methods: {
		// 加载分类列表
		async loadCategories() {
			try {
				const categoryObj = uniCloud.importObject('category')
				const res = await categoryObj.listCategories({
					type: this.form.type
				})
				
				if (res.code === 0) {
					this.categories = res.data
				}
			} catch (e) {
				console.error('加载分类失败', e)
			}
		},
		
		// 加载记录详情（编辑模式）
		async loadRecord() {
			try {
				const accountObj = uniCloud.importObject('account')
				const res = await accountObj.getRecord(this.recordId)
				
				if (res.code === 0) {
					this.form = {
						type: res.data.type,
						amount: String(res.data.amount),
						category_id: res.data.category_id,
						note: res.data.note || '',
						date: res.data.date
					}
					this.loadCategories()
				}
			} catch (e) {
				console.error('加载记录失败', e)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},
		
		// 切换类型
		changeType(type) {
			this.form.type = type
			this.form.category_id = ''
			this.loadCategories()
		},
		
		// 选择分类
		selectCategory(item) {
			this.form.category_id = item._id
		},
		
		// 日期改变
		onDateChange(e) {
			this.form.date = e.detail.value
		},
		
		// 金额输入聚焦
		onAmountFocus() {
			// 可以在这里添加键盘显示的逻辑
		},
		
		// 金额输入失焦
		onAmountBlur() {
			// 格式化金额为两位小数
			if (this.form.amount) {
				const num = parseFloat(this.form.amount)
				if (!isNaN(num)) {
					this.form.amount = num.toFixed(2)
				}
			}
		},
		
		// 提交表单
		async submitForm() {
			if (!this.canSubmit) {
				return
			}
			
			uni.showLoading({
				title: this.isEdit ? '保存中...' : '记账中...'
			})
			
			try {
				const accountObj = uniCloud.importObject('account')
				
				const data = {
					type: this.form.type,
					amount: parseFloat(this.form.amount),
					category_id: this.form.category_id,
					note: this.form.note,
					date: this.form.date
				}
				
				let res
				if (this.isEdit) {
					res = await accountObj.updateRecord(this.recordId, data)
				} else {
					res = await accountObj.addRecord(data)
				}
				
				uni.hideLoading()
				
				if (res.code === 0) {
					uni.showToast({
						title: this.isEdit ? '修改成功' : '记账成功',
						icon: 'success'
					})
					
					setTimeout(() => {
						uni.navigateBack({
							success: () => {
								// 通知列表页刷新
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								if (prevPage) {
									prevPage.$vm.onRefresh()
								}
							}
						})
					}, 1000)
				} else {
					uni.showToast({
						title: res.msg || '操作失败',
						icon: 'none'
					})
				}
			} catch (e) {
				uni.hideLoading()
				console.error('提交失败', e)
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				})
			}
		},
		
		// 跳转到添加分类页面
		goToAddCategory() {
			uni.navigateTo({
				url: `/pages/category/index?type=${this.form.type}`
			})
		},
		
		// 获取今天的日期
		getToday() {
			const date = new Date()
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		}
	}
}
</script>

<style scoped>
.add-account {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
}

/* 类型切换 */
.type-tabs {
	display: flex;
	background-color: #fff;
	padding: 20rpx;
}

.type-tab {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	border-radius: 12rpx;
	transition: all 0.3s;
}

.type-tab.active {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.type-text {
	font-size: 32rpx;
	color: #666;
}

.type-tab.active .type-text {
	color: #fff;
	font-weight: bold;
}

/* 金额输入 */
.amount-section {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 60rpx 40rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
}

.currency {
	font-size: 60rpx;
	color: #333;
	margin-right: 20rpx;
}

.amount-input {
	flex: 1;
	font-size: 80rpx;
	font-weight: bold;
	color: #333;
	text-align: left;
}

.amount-placeholder {
	color: #ccc;
}

/* 分类选择 */
.category-section {
	background-color: #fff;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.category-list {
	white-space: nowrap;
}

.category-item {
	display: inline-block;
	text-align: center;
	margin-right: 30rpx;
	padding: 10rpx;
	border-radius: 12rpx;
	transition: all 0.3s;
}

.category-item.active {
	background-color: #f0f0ff;
}

.category-icon {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 10rpx;
}

.category-item.active .category-icon {
	background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
	transform: scale(1.1);
}

.category-icon .iconfont {
	font-size: 50rpx;
	color: #fff;
}

.category-name {
	font-size: 24rpx;
	color: #666;
	display: block;
}

.add-category .category-icon {
	background: #f5f5f5;
}

.add-category .iconfont {
	color: #999;
	font-size: 60rpx;
	font-weight: 300;
}

/* 表单区域 */
.form-section {
	background-color: #fff;
	padding: 0 20rpx;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
	border-bottom: none;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	width: 120rpx;
}

.form-value {
	flex: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 28rpx;
	color: #333;
}

.form-value .iconfont {
	font-size: 40rpx;
	color: #999;
}

.form-input {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

/* 底部按钮 */
.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	font-size: 32rpx;
	border-radius: 44rpx;
	border: none;
}

.submit-btn[disabled] {
	background: #ddd;
	color: #999;
}
</style>

